<script setup>
import {useStore} from "@/store";
import {ElMessage} from "element-plus";
import LightCard from "@/components/LightCard.vue";
import {getMetadata, getMetadataOfOwner, getTokenURI, tokensOfOwner} from "@/contract/nft";
import {balanceOf} from "@/contract/usdt";
const store = useStore()
//链接钱包
async function connectWallet() {
  //检查浏览器是否有钱包插件
  if (window.ethereum) {
    try {
      // 请求用户授权连接钱包
      const accounts = await window.ethereum.request({method: 'eth_requestAccounts'});
      // 设置第一个账户为当前连接的钱包地址
      store.wallet.address =  accounts[0];
      //显示地址
      store.wallet.connected = true
      //加载账户信息
      store.wallet.tokenIds = await tokensOfOwner(accounts[0])
      store.wallet.tokenURI = await getTokenURI(accounts[0])
      store.wallet.metadata = await getMetadataOfOwner(accounts[0])
      store.wallet.cusdt = await balanceOf(accounts[0])

      //封装nft
      for (let i = 0; i < store.wallet.tokenIds.length; i++) {
        let tokenId = store.wallet.tokenIds[i]
        let metadata = await getMetadata(tokenId)
        store.wallet.nft.push({
          "tokenId":tokenId,
          "metadata":metadata
        })
      }

    } catch (error) {
      // 如果连接钱包过程中出错，打印错误信息
      ElMessage.error('Error connecting to wallet:', error);
    }
  }
}
</script>
<template>
  <div style="top: 20px" >
    <LightCard>
      <div style="text-align: center;padding: 5px 15px 0 15px">
        <el-button type="success" @click="connectWallet" v-if="!store.wallet.connected">连接钱包</el-button>
      </div>
    </LightCard>
  </div>
</template>
<style scoped>

</style>